import datetime
import os
import random
from tornado.escape import json_decode, json_encode
import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.options
from tornado.web import RequestHandler
from tornado.websocket import WebSocketHandler
import json

users = list()  # 存储用户的容器


class IndexHandler(RequestHandler):
    def get(self):
        self.render("index.html")


class UserHandler(RequestHandler):

    def get(self):
        #usernames = [u.username for u in users]
        #print(usernames)
        for u in users:
            print(u.username)
        #self.write(json_encode(usernames))


    def post(self):
        print(self.get_argument('username'))


class ChatHandler(WebSocketHandler):

    # 回复消息模板
    response_msg = {
        "content": "",
        "time": "",
        "send_user": "",
        "to_user": ""
    }
    avatar = ''
    username = ''

    def open(self):
        users.append(self)  # 新来用户添加到存储用户的容器内

    def on_message(self, message):
        try:
            # 接收发送过来的消息
            msg = json.loads(message)
            msg_type = msg.get('type', '')
            msg_content = msg.get('msg', '')
            if msg_type == 'login':
                # 随机头像
                self.avatar = self.random_avatar()
                self.username = msg_content  # 保存用户名
                self.response_msg["content"] = "{} 进入聊天室".format(self.username)
            elif msg_type == 'msg':
                self.response_msg["content"] = msg_content
            self.response_msg["time"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            self.response_msg["send_user"] = self.username
            self.response_msg["avatar"] = self.avatar
            response_msg_content = json.dumps(self.response_msg)
            for u in users:
                u.write_message(response_msg_content)
        except:
            pass

    def on_close(self):
        self.response_msg["time"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.response_msg["send_user"] = self.username
        self.response_msg["content"] = "{} 离开聊天室".format(self.username)
        response_msg_content = json.dumps(self.response_msg)
        users.remove(self)  # 用户关闭连接后，从容器中删除这个用户
        for u in users:
            u.write_message(response_msg_content)

    def check_origin(self, origin):
        return True

    def random_avatar(self):
        avatar_path = 'static/avatar/'
        random_avator = random.sample(os.listdir(avatar_path), 1)[0]
        return avatar_path + random_avator


if __name__ == '__main__':
    tornado.options.parse_command_line()
    app = tornado.web.Application(
        [
            (r"/", IndexHandler),
            (r"/chat", ChatHandler),
            (r"/user", UserHandler)
        ],
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        template_path=os.path.join(os.path.dirname(__file__), "template"),
        debug=True
    )
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(8090)
    tornado.ioloop.IOLoop.current().start()
